<template>
  <searchrevealing>
    <el-form ref="queryFormRef" :model="queryParam" :inline="true" label-width="97px">
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="queryParam.deptName" placeholder="请输入" clearable style="width: 220px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="出库可选状态" prop="isOutStock">
        <el-select v-model="queryParam.isOutStock" placeholder="请选择" clearable filterable style="width: 220px">
          <el-option v-for="dict in outboundList" :key="dict.userId" :label="dict.nickName" :value="dict.userId" />
        </el-select>
      </el-form-item>

    </el-form>
    <div class="form_button">
      <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
      <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
    </div>
  </searchrevealing>
  <el-card shadow="never">
    <template #header>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Open" @click="handleOpen()" :disabled="multipleOpen">启用
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="TurnOff" @click="handleTurnOff()" :disabled="multipleOff">禁用
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" @click="handleDelete()" :disabled="multipledisabled">删除
          </el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'产品出库部门管理'"
          @updateColumn="getColmun"></right-toolbar>
      </el-row>
    </template>
    <el-table v-loading="loading" :data="selectionRecordList" border @selection-change="handleSelectionChange"
      @header-dragend="dragEnd">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-for="(item, index) in inventoryRecordColumns" :key="index" :label="item.label" align="center"
        :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
        <template #default="scope">
          <span v-if="item.prop == 'isOutStock'">
            <el-switch v-model="scope.row.isOutStock" :active-value="0" :inactive-value="2"
              :before-change="() => onchange(scope.row.isOutStock, scope.row.outDeptId, scope.row.deptName)"></el-switch>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleDelete(scope.row)" class="color_theme">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParam.pageNum" v-model:limit="queryParam.pageSize"
      @pagination="paginationChange" />
  </el-card>
  <!-- 添加或修改参数配置对话框 -->
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
    <el-form ref="dictFormRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="新增部门" prop="deptId">
        <el-tree-select v-model="form.deptId" :data="deptOptions" show-checkbox multiple check-strictly="true"
          :props="{ value: 'id', label: 'label', children: 'children', disabled: 'isChecked' }" value-key="id"
          placeholder="请选择" style="width: 350px" />
      </el-form-item>
      <el-form-item label="出库可选" prop="isOutStock">
        <el-select v-model="form.isOutStock" placeholder="请选择" clearable filterable style="width: 350px">
          <el-option v-for="dict in outboundList" :key="dict.userId" :label="dict.nickName" :value="dict.userId" />
        </el-select>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="addLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="InventoryDepartment" lang="ts">
const { proxy } = getCurrentInstance() as any;
import { getOutDeptList, updateByIds, deleteByIds, addOutDept, deptTreeSelect } from '@/api/group/productOutbound/index';
import { InventoryDepartmentQueryParmas, InventoryDepartmentVo } from '@/api/group/productOutbound/types';
const queryFormRef = ref<ElFormInstance>();
import { DeptVO } from '@/api/system/dept/types';
import { listColumn } from '@/api/system/column';
const dictFormRef = ref<ElFormInstance>();
const queryParam = ref<InventoryDepartmentQueryParmas>({
  pageNum: 1,
  pageSize: 10,
  deptName: undefined,
  isOutStock: undefined
});
const columnData = ref();
const inventoryRecordColumns = ref();
const selectionRecordList = ref<InventoryDepartmentVo[]>([]);
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);
const addLoading = ref(false);
// 出库可选状态
const outboundList = ref<{ nickName: string; userId: string }[]>([
  { nickName: '启用', userId: '0' },
  { nickName: '禁用', userId: '2' }
]);
const ids = ref<Array<number | string>>([]);
const names = ref<Array<string>>([]);
// loading
const queryLoading = ref(false);
// 多选删除禁用
const multipledisabled = ref(true);
// 启用
const multipleOpen = ref(true);
// 禁用
const multipleOff = ref(true);
// 部门
const deptOptions = ref<DeptVO[]>([]);
// 新增出库
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
interface AddTypeForm {
  deptId?: string[];
  isOutStock?: string;
  pageNum?: number;
  pageSize?: number;
}
const initFormData: AddTypeForm = {
  deptId: [],
  isOutStock: undefined
};

const data = reactive<PageData<AddTypeForm, AddTypeForm>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: [],
    isOutStock: ''
  },
  rules: {
    deptId: [{ required: true, message: '新增部门不能为空', trigger: 'change' }],
    isOutStock: [{ required: true, message: '出库可选不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
/** 搜索按钮操作 */
const handleQuery = () => {
  queryLoading.value = true;
  queryParam.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: InventoryDepartmentVo[]) => {
  ids.value = selection.map((item) => item.outDeptId);
  names.value = selection.map((item) => item.deptName);
  multipledisabled.value = !selection.length;
  multipleOpen.value = !selection.filter((item) => item.isOutStock == '2').length;
  multipleOff.value = !selection.filter((item) => item.isOutStock == '0').length;
};
/** 查询列表 */
const getList = async () => {
  try {
    loading.value = true;
    const res = await getOutDeptList({
      ...queryParam.value
    });
    selectionRecordList.value = res.rows;
    total.value = res.total;
    loading.value = false;
    queryLoading.value = false;
  } catch (e) {
  } finally {
    loading.value = false;
  }
};
/** 切换switch */
const onchange = async (val: string, outDeptId: string, name: string) => {
  // 开启
  if (val == '2') {
    await proxy?.$modal.confirm('是否确认启用"' + name + '"的数据项？');
    await updateByIds({
      ids: [outDeptId],
      isOutStock: 0
    });
    proxy?.$modal.msgSuccess('启用成功');
    return true;
  } else {
    await proxy?.$modal.confirm('是否确认禁用"' + name + '"的数据项？');
    await updateByIds({
      ids: [outDeptId],
      isOutStock: 2
    });
    proxy?.$modal.msgSuccess('禁用成功');
    return true;
  }
};
/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await deptTreeSelect();
  // 删除第一级 ==> 惠迈集团
  deptOptions.value = res.data[0].children;
};
/** 获取colmun */
const getColmun = async () => {
  const columnDatas = await proxy?.useColumn('产品出库部门管理');
  inventoryRecordColumns.value = columnDatas.columnCustom;
  columnData.value = columnDatas;
  queryParams.value.pageSize = columnDatas.columnPageSize || 10;
};
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
  columnData.value.columnCustom.map((item: any) => {
    if (item.prop == column.property) {
      item.width = newWidth;
    }
  });
  await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize);
};
/** 页数变化 */
const paginationChange = async () => {
  await getList();
  await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize);
  getColmun()
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  dictFormRef.value?.resetFields();
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getTreeSelect();
  dialog.visible = true;
  dialog.title = '新增出库部门';
};
/** 提交按钮 */
const submitForm = () => {
  dictFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      addLoading.value = true;
      try {
        await addOutDept({
          ids: form.value.deptId,
          isOutStock: form.value.isOutStock
        });
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        addLoading.value = false;
        getList();
      } catch (err) {
        addLoading.value = false;
      }
    }
  });
};
/** 启用 */
const handleOpen = async () => {
  const dictIds = ids.value;
  await proxy?.$modal.confirm('是否确认启用"' + names.value + '"的数据项？');
  await updateByIds({
    ids: dictIds,
    isOutStock: 0
  });
  getList();
  proxy?.$modal.msgSuccess('启用成功');
};
/** 禁用 */
const handleTurnOff = async () => {
  const dictIds = ids.value;
  await proxy?.$modal.confirm('是否确认禁用"' + names.value + '"的数据项？');
  await updateByIds({
    ids: dictIds,
    isOutStock: 2
  });
  getList();
  proxy?.$modal.msgSuccess('禁用成功');
};
/** 删除 */
const handleDelete = async (row?: InventoryDepartmentVo) => {
  const dictIds = row?.outDeptId ? [row?.outDeptId] : ids.value;
  const name = row?.deptName || names.value;
  await proxy?.$modal.confirm('是否删除禁用编号为"' + name + '"的数据项？');
  await deleteByIds({
    ids: dictIds
  });
  getList();
  proxy?.$modal.msgSuccess('删除成功');
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
onMounted(async () => {
  await getColmun();
  await getList();
  getTreeSelect(); // 初始化部门数据
});
</script>
<style lang="scss" scoped>
.flex_div {
  display: flex;
  align-items: center;

  div {
    width: 144px;
    height: 38px;
    border-radius: 5px;
    text-align: center;
    line-height: 38px;
  }

  .add {
    border: 1px solid #0094ff;
    font-weight: 400;
    font-size: 16px;
    color: #0094ff;
    margin-right: 30px;
  }

  .disabled {
    border: 1px solid #fc2540;
    font-weight: 400;
    font-size: 16px;
    color: #fc2540;
    margin-right: 30px;
  }

  .disableds {
    background: #fc2540;
    font-weight: 400;
    font-size: 16px;
    color: #ffffff;
  }
}
</style>